package com.anti.jdbc;

import com.anti.commom.constant.ExpEnumConstant;
import com.anti.commom.core.exception.BusinessException;
import com.anti.commom.core.utils.StringUtils;
import com.anti.jdbc.core.EntityJdbcOperations;
import com.anti.jdbc.core.SqlJdbcOperations;
import com.anti.jdbc.core.executor.BatchInsertExecutor;
import com.anti.jdbc.core.executor.BatchUpdateExecutor;
import com.anti.jdbc.core.executor.InsertExecutor;
import com.anti.jdbc.core.executor.UpdateExecutor;
import com.anti.jdbc.core.executor.pojo.InsertMode;
import com.anti.jdbc.core.executor.supporrt.JdbcBuilder;
import com.anti.jdbc.core.storeprocedure.*;
import com.anti.jdbc.support.*;
import com.anti.jdbc.support.mapper.BeanRowMapper;
import com.anti.jdbc.support.mapper.MapRowMapper;
import com.anti.jdbc.support.page.PageParam;
import com.anti.jdbc.support.page.PageResult;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author anTi
 * @Date 2021-3-12
 */
public class BaseJdbcTemplate extends JdbcAccessor implements SqlJdbcOperations, EntityJdbcOperations {
    private static Logger log = LoggerFactory.getLogger(BaseJdbcTemplate.class);

    public BaseJdbcTemplate() {
    }

    public BaseJdbcTemplate(DataSource dataSource) {
        this.setDataSource(dataSource);
        this.afterPropertiesSet();
    }

    public BaseJdbcTemplate(DataSource dataSource, boolean lazyInit) {
        this.setDataSource(dataSource);
        this.setLazyInit(lazyInit);
        this.afterPropertiesSet();
    }


    @Override
    public <R> R queryForObject(String sql, Class<R> cls, Object... params) {
        return this.jdbcQueryForObject(sql, params, new BeanRowMapper<>(cls));
    }

    @Override
    public <R> Object getValue(String sql, Class<R> cls, Object... params) {
        return this.queryForObject(sql,cls,params);
    }

    @Override
    public Map<String, Object> get(String sql, Object... params) {
        return this.jdbcQueryForObject(sql, params, new MapRowMapper());
    }

    @Override
    public <R> R get(String sql, Class<R> cls, Object... params) {
        return jdbcQueryForObject(sql, params, new BeanRowMapper<>(cls));
    }

    @Override
    public <R> R getFirst(String sql, Class<R> cls, Object... params) {
        sql = SqlUtils.buildLimitSql(sql, this.getDataBaseType(), 0L, 1L);
        List<R> query = this.query(sql, cls, params);
        return query.size() == 0 ? null : query.get(0);
    }

    @Override
    public Map<String, Object> getFirst(String sql, Object... params) {
        sql = SqlUtils.buildLimitSql(sql, this.getDataBaseType(), 0L, 1L);
        List<Map<String, Object>> query = this.query(sql,params);
        return query.size() == 0 ? null : query.get(0);
    }

    @Override
    public <R> List<R> query(String sql, Class<R> cls, Object... params) {
        List<R> result = this.jdbcQuery(sql, params, new BeanRowMapper<>(cls));
        return result == null ? new ArrayList() : result;
    }
    @Override
    public List<Map<String, Object>> query(String sql, Object... params) {
        List<Map<String, Object>> result = this.jdbcQuery(sql, params, new MapRowMapper());
        return result == null ? new ArrayList() : result;
    }

    @Override
    public PageResult query(PageParam pageParam, String sql, Object... params) {
        return this.queryForPage(pageParam, sql, new MapRowMapper(), params);
    }

    @Override
    public <R> PageResult query(PageParam pageParam, String sql, Class<R> cls, Object... params) {
        return this.queryForPage(pageParam, sql, new BeanRowMapper<>(cls), params);
    }

    @Override
    public int execSql(String sql, Object... params) {
        SqlArgument trueArgument = SqlUtils.getSqlArgument(sql, params);
        if (log.isDebugEnabled()) {
            log.debug(trueArgument.getText());
        }

        int rows;
        if (trueArgument.isNamedQuery()) {
            rows = this.getNamedJdbcTemplate().update(trueArgument.getText(), trueArgument.getParamMap());
        } else {
            rows = this.getJdbcTemplate().update(trueArgument.getText(), trueArgument.getArgs());
        }
        return rows;
    }


    @Override
    public void executeProcedure(SpSupportBean spSupportBean) {
        final SpBeanParamters spBeanParamters = SpBeanParamterBuilder.build(spSupportBean.getClass());
        this.getJdbcTemplate().execute(con -> {
            StringBuilder sb = new StringBuilder(100);
            sb.append("{call ").append(spSupportBean.getSpName());
            if (spBeanParamters.getCount() > 0) {
                sb.append("(?");
                sb.append(StringUtils.repeat(",?", spBeanParamters.getCount() - 1));
                sb.append(")");
            } else {
                sb.append("}");
            }

            CallableStatement cs = con.prepareCall(sb.toString());
            int i = 1;

            while(i <= spBeanParamters.getCount()) {
                SpBeanParamter spBeanParamter = spBeanParamters.getParamter(i);
                if (spBeanParamter == null) {
                    throw new BusinessException(ExpEnumConstant.SERVER_EXCEPTION_ENUM,"参数" + i + "定义缺失");
                }
                Object value = null;

                try {
                    value = PropertyUtils.getProperty(spSupportBean, spBeanParamter.getName());
                } catch (IllegalAccessException var8) {
                    var8.printStackTrace();
                } catch (InvocationTargetException var9) {
                    var9.printStackTrace();
                } catch (NoSuchMethodException var10) {
                    var10.printStackTrace();
                }

                if (value != null && "java.util.Date".equals(value.getClass().getName())) {
                    value = new Date(((java.util.Date)value).getTime());
                }

                ParamInOut paramType = spBeanParamter.getInOut();
                switch(paramType) {
                    case IN:
                    case INOUT:
                        if (value == null) {
                            cs.setNull(i, spBeanParamter.getType());
                        } else {
                            cs.setObject(i, value);
                        }
                    default:
                        switch(paramType) {
                            case INOUT:
                            case OUT:
                                cs.registerOutParameter(i, spBeanParamter.getType());
                            default:
                                ++i;
                        }
                }
            }

            return cs;
        }, (CallableStatementCallback) cs -> {
            cs.execute();
            for(int i = 1; i <= spBeanParamters.getCount(); ++i) {
                SpBeanParamter spBeanParamter = spBeanParamters.getParamter(i);
                if (spBeanParamter.getInOut() != ParamInOut.IN) {
                    Object value = cs.getObject(i);

                    try {
                        PropertyUtils.setSimpleProperty(spSupportBean, spBeanParamter.getName(), value);
                    } catch (IllegalAccessException var6) {
                        var6.printStackTrace();
                    } catch (InvocationTargetException var7) {
                        var7.printStackTrace();
                    } catch (NoSuchMethodException var8) {
                        var8.printStackTrace();
                    }
                }
            }
            return true;
        });
    }

    @Override
    public <R> R executeFunction(String fun, Class<R> cls, Object... params) {
        return this.getJdbcTemplate().execute((CallableStatementCreator) con -> {
            StringBuilder sb = new StringBuilder(100);
            sb.append("{ ? = call ").append(fun);
            if (params != null && params.length > 0) {
                sb.append("(?");
                sb.append(StringUtils.repeat(",?", params.length - 1));
                sb.append(")");
            } else {
                sb.append("}");
            }

            CallableStatement cs = con.prepareCall(sb.toString());
            cs.registerOutParameter(1, SpParamTypeMapping.getSqlType(cls));
            if (params != null) {
                for(int i = 0; i < params.length; ++i) {
                    if (params[i] != null && "java.util.Date".equals(params[i].getClass().getName())) {
                        cs.setObject(i + 2, new Date(((java.util.Date)params[i]).getTime()));
                    } else {
                        cs.setObject(i + 2, params[i]);
                    }
                }
            }

            return cs;
        }, cs -> {
            cs.execute();
            return (R) cs.getObject(1);
        });
    }

    ////////////////////////////////////////////////////////////////////////////////////
    private <R> List<R> jdbcQuery(String sql, Object[] params, RowMapper<R> rowMapper) {
        SqlArgument trueArgument = SqlUtils.getSqlArgument(sql, params);
        if (log.isDebugEnabled()) {
            log.debug(trueArgument.getText());
        }
        List list;
        if (trueArgument.isNamedQuery()) {
            list = this.getNamedJdbcTemplate().query(trueArgument.getText(), trueArgument.getParamMap(), rowMapper);
        } else {
            list = this.getJdbcTemplate().query(trueArgument.getText(), trueArgument.getArgs(), rowMapper);
        }

        return list;
    }

    private <R> R jdbcQueryForObject(String sql, Object[] params, RowMapper<R> rowMapper) {
        SqlArgument trueArgument = SqlUtils.getSqlArgument(sql, params);
        if (log.isDebugEnabled()) {
            log.debug(trueArgument.getText());
        }
        R result;
        if (trueArgument.isNamedQuery()) {
            result = this.getNamedJdbcTemplate().queryForObject(trueArgument.getText(), trueArgument.getParamMap(), rowMapper);
        } else {
            result = this.getJdbcTemplate().queryForObject(trueArgument.getText(), trueArgument.getArgs(), rowMapper);
        }

        return result;
    }
    private <R> PageResult queryForPage(PageParam pageParam, String sql, RowMapper<R> rowMapper, Object[] params) {
        PageResult pageResult = new PageResult();
        pageResult.setPageSize(pageParam.getPageSize());
        pageResult.setPageIndex(pageParam.getPageIndex());
        String noOrderSql = SqlUtils.removeOrders(sql);
        StringBuilder countSql = new StringBuilder();
        countSql.append("select count(*) total ");
        if (StringUtils.isNotBlank(pageParam.getAggregate())) {
            countSql.append(",").append(pageParam.getAggregate());
        }

        countSql.append(" from (").append(noOrderSql).append(") cnt_ ");
        Map<String, Object> summary = this.get(countSql.toString(), params);
        Integer total = 0;
        if (null!=summary) {
            Number totalNum = (Number)summary.get("total");
            if (totalNum != null) {
                total = totalNum.intValue();
            }
        }
        pageResult.setTotal(total);
        Object result;
        if (total < 1L) {
            result = new ArrayList();
        } else {
            boolean hasSort = StringUtils.isNotBlank(pageParam.getSortField());
            boolean hasOrder = StringUtils.isNotBlank(pageParam.getOrder());
            if (hasSort || hasOrder) {
                StringBuilder orderSql = new StringBuilder();
                orderSql.append("select * from (").append(noOrderSql).append(") result order by ");
                if (hasSort) {
                    orderSql.append(pageParam.getSortField()).append(" ").append(pageParam.getSortOrder()).append(" ");
                    if (hasOrder) {
                        orderSql.append(",");
                    }
                }

                if (hasOrder) {
                    orderSql.append(pageParam.getOrder());
                }

                sql = orderSql.toString();
            }

            long pageSize = pageParam.getPageSize();
            if (pageSize <= 0L) {
                pageSize = 20L;
            }

            long start = pageParam.getPageIndex() * pageSize;
            sql = SqlUtils.buildLimitSql(sql, this.getDataBaseType(), start, pageSize);
            result = this.jdbcQuery(sql, params, rowMapper);
        }

        pageResult.setData((List)result);
        return pageResult;
    }


    /////////////////////////////////////////persistent//////////////////////////////////////////


    @Override
    public int insert(Object persistent) {
        Assert.notNull(persistent, "Entities cannot be empty");
        InsertExecutor executor = new InsertExecutor(getJdbcBuilder(), persistent, InsertMode.IGNORENULL);
        int rows = (int) executor.execute();
        executor = null;
        return rows;
    }

    @Override
    public int insertWithNull(Object persistent) {
        Assert.notNull(persistent, "Entities cannot be empty");
        InsertExecutor executor = new InsertExecutor(getJdbcBuilder(), persistent);
        int rows = (int) executor.execute();
        executor = null;
        return rows;
    }

    @Override
    public Object insertKey(Object persistent) {
        Assert.notNull(persistent, "Entities cannot be empty");
        InsertExecutor executor = new InsertExecutor(getJdbcBuilder(), persistent,true,InsertMode.IGNORENULL);
        Object rows = (Object) executor.execute();
        executor = null;
        return rows;
    }

    @Override
    public int batchInsert(List<?> persistents) {
        Assert.notEmpty(persistents, "Entity list cannot be empty");
        BatchInsertExecutor executor = new BatchInsertExecutor(getJdbcBuilder(),persistents);
        int[] rows = executor.execute();
        executor = null;
        return rows.length;
    }


    @Override
    public int update(Object persistent) {
        Assert.notNull(persistent, "Entities cannot be empty");
        UpdateExecutor executor = new UpdateExecutor(getJdbcBuilder(),persistent,true);
        int rows = executor.execute();
        executor = null;
        return rows;
    }

    @Override
    public int batchUpdate(List<?> persistents) {
        Assert.notEmpty(persistents, "Entity list cannot be emp");
        BatchUpdateExecutor executor = new BatchUpdateExecutor(getJdbcBuilder(),persistents);
        int[] rows = executor.execute();
        executor = null;
        return rows.length;
    }

    public JdbcBuilder getJdbcBuilder(){
        JdbcBuilder jdbcBuilder=new JdbcBuilder(getJdbcTemplate(),false, isShowSQL(),getInterfaceClass());
        return jdbcBuilder;
    }
}
